var express = require('express');
var router = express.Router();
const { listModel, cateModel } = require("../model/model");
const { log } = require('debug/src/browser');

router.post('/addcate', async (req, res) => {
    await cateModel.create(req.body)
    res.send({
        code: 200
    })
})

router.get('/getcate', async (req, res, next) => {
    try {
        let data = await cateModel.find({})
        res.status(200).json(data);
    } catch (err) {
        next(err);
    }
})

router.post('/addlist', async (req, res, next) => {
    try {
        const list = await new listModel(req.body).save();
        res.send({
            code: 200,
            data: list
        });
    } catch (err) {
        next(err);
    }
})

router.get('/getList', async (req, res) => {
    try {
        let data = await listModel.find({}).populate("cid")
        res.status(200).json(data);
    } catch (err) {
        next(err);
    }
})

router.get('/search', async (req, res, next) => {
    try {
        let { searchtext } = req.query;

        const regex = new RegExp(searchtext);

        let data = await listModel.find({ name: regex }).populate("cid")

        res.status(200).json(data);
    } catch (err) {
        next(err);
    }
})

router.get('/getcatelist', async (req, res, next) => {

    try {
        let { searchid } = req.query;
        console.log(searchid);

        if (searchid != 'all') {
            let data = await listModel.find({ cid: searchid }).populate("cid")
            res.status(200).json(data);
        } else {
            let data = await listModel.find({}).populate("cid")

            res.status(200).json(data);
        }
    } catch (err) {
        next(err);
    }
})






module.exports = router;
